﻿using System;
using Microsoft.Win32;
using Microsoft.Deployment.WindowsInstaller;

namespace PerformanceDude.MSBuildShellExtension.Cleaner
{
    public class CustomAction
    {
        [CustomAction]
        public static ActionResult Clean(Session session)
        {
            try
            {
                session.Log("Begin Clean");

                var domainModelFacade = DomainModelFacade.Instance;

                foreach (var extension in domainModelFacade.Extensions)
                {
                    foreach (var target in domainModelFacade.Targets)
                    {
                        var key = "SystemFileAssociations\\." + extension.FileExtension + "\\shell\\" + target.Title;
                        try
                        {
                            Registry.ClassesRoot.DeleteSubKeyTree(key);
                        }
                        catch (Exception)
                        {
                            // Ignored
                        }
                    }
                }

                try
                {
                    Registry.CurrentUser.DeleteSubKeyTree("Software\\Ardal\\MSBuildShellExtension\\Editors");
                    Registry.CurrentUser.DeleteSubKeyTree("Software\\Ardal\\MSBuildShellExtension\\Targets");
                    Registry.CurrentUser.DeleteSubKeyTree("Software\\Ardal\\MSBuildShellExtension\\Extensions");
                    Registry.CurrentUser.DeleteSubKeyTree("Software\\Ardal\\MSBuildShellExtension");
                }
                catch (Exception)
                {
                    // Ignored
                }

                return ActionResult.Success;
            }
            catch (Exception ex)
            {
                session.Log(ex.ToString());
                return ActionResult.Failure;
            }
        }
    }
}
